package graphics;

import data.Map;
import data.Player;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;

/**
 * graphics
 *
 * @author Jared Moore
 * @date 10/16/13
 */
public class OuterPanel extends JPanel {

	private int timeLeft;
	private final JLabel label, label1;
	private Timer timer;

	/**
	 * initializes the map-independent part of the GUI that shows information
	 * relevant to the current player including the name of the current player, money and time left
	 *
	 * @param map The map to be used
	 */
	public OuterPanel(final Map map, boolean isLoaded) {
		timeLeft = map.getTurnLength(map.getCurrentPlayer()) / 1000;
		setSize(800, 600);
		setLayout(new BorderLayout());

		JPanel panel = new JPanel();

		label = new JLabel("Time Left:  50");
		label1 = new JLabel(String.format("Current Player:  %s,  ", map.getCurrentPlayer().toString()));
		panel.add(label1, BorderLayout.EAST);
		timer = new Timer(1000, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				String text = label.getText();
				text = text.substring(12);
				Scanner scanner = new Scanner(text);
				timeLeft = scanner.nextInt();
				if (--timeLeft == 0) {
					timeLeft = map.getTurnLength(map.getCurrentPlayer()) / 1000;
				}
				label.setText(String.format("Time Left:  %d ", timeLeft));
				label1.setText(map.getCurrentPlayer().toString());
			}
		});
		panel.add(label, BorderLayout.WEST);
		add(panel, BorderLayout.NORTH);
		setFocusable(true);
		add(new MULEPanel(map, this, isLoaded), BorderLayout.CENTER);
	}

	public int getTimeLeft() {
		return timeLeft;
	}

	public void resetTime(int time) {
		timeLeft = time / 1000;
		repaint();
	}


	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		label.setText(String.format("Time Left:  %d", timeLeft));
	}

	public void timerSwitch(boolean on) {
		if (on) {
			timer.start();
		} else {
			timer.stop();
		}
	}

	public boolean getTimer() {
		return timer.isRunning();
	}

	public void setPlayer(Player curr) {
		label1.setText(String.format("Current Player: %s, Money: %d,", curr.getName(), curr.getMoney()));
	}
}
